let utils = require('../utils/util');
import { config } from '~/config/index';

// 获取三位数随机数
const random1 = utils.getRandomNumber(100, 999);
const random2 = utils.getRandomNumber(100, 999);
let timer1 = null;
let timer2 = null;

export const request = ({ url, method = 'GET', data, succStatus = false }) => {
  return new Promise((resolve, reject) => {
    const token = wx.getStorageSync('token') || '';
    wx.request({
      url: config.baseUrl + url,
      method: method,
      data,
      header: {
        'Content-type': 'application/json;charset=utf-8',
        token: token,
        unique: `${random1}xysx68jd106kl39g${random2}`,
      },
      success(res) {
        if (res.statusCode === 200) {
          if (res?.data) {
            const resData = res.data;
            // code:200 成功状态
            if (resData.code == 200) {
              succStatus ? resolve(resData) : resolve(resData.data);
            } else {
              if (!resData.status && ['Invalid token,请重新登录', 'empty token,请重新登录'].includes(resData.msg)) {
                // 节流处理，同一时间只执行一次
                if (timer1) return;
                timer1 = setTimeout(() => {
                  wx.removeStorageSync('token');
                  // 返回首页
                  wx.switchTab({ url: '/pages/home/home' });
                  timer1 = null;
                }, 500);
              }
              // 节流处理，同一时间只暴露一个错误信息
              if (timer2) return;
              timer2 = setTimeout(() => {
                wx.showModal({
                  content: resData.msg,
                  showCancel: false,
                });
                timer2 = null;
              }, 500);
              reject(resData.msg);
            }
          } else {
            reject(res.errMsg);
          }
        } else {
          let error = {};
          switch (res.statusCode) {
            case 400:
              error.msg = '请求错误(400)';
              break;
            case 401:
              error.msg = '未授权，请重新登录(401)';
              // wx.navigateTo({ url: '/pages/auth/index', })
              break;
            case 403:
              error.msg = '拒绝访问(403)';
              break;
            case 404:
              error.msg = '请求出错(404)';
              break;
            case 408:
              error.msg = '请求超时(408)';
              break;
            case 500:
              error.msg = '服务器错误(500)';
              break;
            case 501:
              error.msg = '服务未实现(501)';
              break;
            case 502:
              error.msg = '网络错误(502)';
              break;
            case 503:
              error.msg = '服务不可用(503)';
              break;
            case 504:
              error.msg = '网络超时(504)';
              break;
            case 505:
              error.msg = 'HTTP版本不受支持(505)';
              break;
            default:
              error.msg = `连接出错(${res.statusCode})!`;
          }
          wx.showModal({ content: error.msg, showCancel: false });
          reject(error);
        }
      },
      fail(err) {
        console.log('err::', err);
        reject(err);
      },
    });
  });
};
